package org.jsola.hr.web;

import org.apache.commons.lang3.StringUtils;
import org.jsola.admin.entity.DictItemDO;
import org.jsola.cache.ICache;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.CacheKeyKit;
import org.jsola.hr.common.wechat.AccessToken;
import org.jsola.hr.common.wechat.JumpWxa;
import org.jsola.hr.common.wechat.MessageHandlerUtil;
import org.jsola.hr.constant.ConfigCodeConstants;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.ZtcConfigAddDTO;
import org.jsola.hr.dto.ZtcConfigUpdateDTO;
import org.jsola.hr.dto.syncSocDTO.QdAttritionCheckDTO;
import org.jsola.hr.dto.syncSocDTO.QdEmploymentRegistrationUnit;
import org.jsola.hr.dto.syncSocDTO.QdIncrementCheckDTO;
import org.jsola.hr.dto.syncSocDTO.ZtcAccessTokenDTO;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.provider.ISiteConfigProviderService;
import org.jsola.hr.query.ZtcConfigQuery;
import org.jsola.hr.service.IZtcConfigService;
import org.jsola.hr.vo.ZtcConfigListVO;
import org.jsola.hr.vo.ZtcConfigVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * 微信相关接口
 *
 * @author zhr
 */
@RestController("wxController")
@RequestMapping(HrConstants.API_PATH + "/v1/wx")
public class WxController {

    @Autowired
    private ISiteConfigProviderService siteConfigProviderService;

    @Autowired
    private ICache cache;

    /**
     * 获取小程序 scheme 码
     * 参考文档：
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.generate.html
     * @return
     */
    @GetMapping("/getOpenLink")
    public Result<String> getOpenLink() {

        // 小程序appid
        String appid = siteConfigProviderService.selectValueByCode(ConfigCodeConstants.CODE_MINI_APPID, null);

        String key = CacheKeyKit.getAccessToken(appid);
        String access_token = cache.get(key);
        if (StringUtils.isBlank(access_token)) {
            // 小程序appSecret
            String secret = siteConfigProviderService.selectValueByCode(ConfigCodeConstants.CODE_MINI_SECRET, null);
            AccessToken accessToken = MessageHandlerUtil.getAccessToken(appid, secret);
            cache.set(key, accessToken.getAccessToken(), (accessToken.getExpiresin() - 10)  * 1000);
            access_token = accessToken.getAccessToken();
        }

        JumpWxa jumpWxa = new JumpWxa();
        jumpWxa.setPath("/pages/index/index");
        String openLink = MessageHandlerUtil.getOpenLink(access_token, jumpWxa);
        return Result.success(openLink);
    }

}

